package org.fuyd.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.fuyd.manager.CustomerManager;
import org.fuyd.model.Customer;
import org.fuyd.util.EncryptySHA1;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport {

  /**
   * 
   */
  private static final long serialVersionUID = 1355354279184141583L;

  private String address; // 用户地址
  private CustomerManager customerManager; // 该成员变量是由Spring管理，用来进行注入。
  private List<Customer> customers;

  private InputStream inputStream; // 该成员变量用于将结果返回给前台AJAX。

  private String password; // 密码

  private String username; // 用户名

  /**
   * 添加一个客户，用于客户注册。
   * 
   * @return
   */
  public String add() {
    // 创建一个客户
    Customer customer = new Customer();
    customer.setUsername(username);
    // 对客户密码取SHA1值得操作
    this.password = new EncryptySHA1().getSHA1CodeOfString(password);
    customer.setPassword(password);
    // 添加客户
    this.customerManager.add(customer);
    return SUCCESS;
  }

  /**
   * 判断用户是否存在，用于前台的AJAX。
   * 
   * @return
   * @throws UnsupportedEncodingException
   */
  public String exist() throws UnsupportedEncodingException {
    Map<String, String> map = new HashMap<String, String>();
    
    if (this.customerManager.exist(username)) {
      map.put("ErrorCode", "-100");
      map.put("ErrorReason", "该用户名已存在");
    } else {
      map.put("ErrorCode", "0");
      map.put("ErrorReason", "恭喜您，该用户名可以注册！");
    }
    String result = JSONObject.toJSONString(map);
    this.inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));
    return "check";

  }

  public String findAll() {
    this.customers = this.customerManager.findAll();
    return "list";
  }

  public String getAddress() {
    return address;
  }

  public CustomerManager getCustomerManager() {
    return customerManager;
  }

  public List<Customer> getCustomers() {
    return customers;
  }

  public InputStream getInputStream() {
    return inputStream;
  }

  public String getPassword() {
    return password;
  }

  public String getUsername() {
    return username;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public void setCustomerManager(CustomerManager customerManager) {
    this.customerManager = customerManager;
  }

  public void setCustomers(List<Customer> customers) {
    this.customers = customers;
  }

  public void setInputStream(InputStream inputStream) {
    this.inputStream = inputStream;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public void setUsername(String username) {
    this.username = username;
  }

}
